import { useAuthStore, usePermissionStore, useUserStore } from '@/store'
import api from '@/api'
import { getUserInfo } from '@/store/helper'

const WHITE_LIST = ['/login', '/404']
export function createPermissionGuard(router) {
  router.beforeEach(async (to) => {
    const authStore = useAuthStore()
    const token = authStore.accessToken
    /** 没有token */
    if (!token) {
      if (WHITE_LIST.includes(to.path)) return true
      return { path: 'login', query: { ...to.query, redirect: to.path } }
    }

    // 有token的情况
    if (to.path === '/login') return { path: '/' }
    if (WHITE_LIST.includes(to.path)) return true

    const userStore = useUserStore()
    const permissionStore = usePermissionStore()
    if (!userStore.userInfo) {
      let [user, permissions] = await Promise.all([getUserInfo()])
      permissions = [
        {
          id: 1,
          name: '竞拍审核',
          code: 'GoodsMgt',
          type: 'MENU',
          parentId: null,
          path: '/',
          redirect: null,
          icon: 'i-fe:briefcase',
          component: '/src/views/goods/index.vue',
          layout: null,
          keepAlive: null,
          method: null,
          description: null,
          show: true,
          enable: true,
          order: 1,
          children: [
            {
              id: 111,
              name: '创建商品',
              // code: 'AddGoods',
              type: 'BUTTON',
              parentId: 1,
              path: null,
              redirect: null,
              icon: null,
              component: null,
              layout: null,
              keepAlive: null,
              method: null,
              description: null,
              show: true,
              enable: true,
              order: 1,
            },
          ],
        },
        {
          id: 2,
          name: '竞拍管理',
          code: 'competeMgt',
          type: 'MENU',
          parentId: null,
          path: '/compete',
          redirect: null,
          icon: 'i-fe:shopping-bag',
          component: '/src/views/compete/index.vue',
          layout: null,
          keepAlive: false,
          method: null,
          description: null,
          show: true,
          enable: true,
          order: 2,
          children: [
            {
              id: 222,
              name: '创建商品',
              code: 'AddGoods',
              type: 'BUTTON',
              parentId: 1,
              path: null,
              redirect: null,
              icon: null,
              component: null,
              layout: null,
              keepAlive: null,
              method: null,
              description: null,
              show: true,
              enable: true,
              order: 1,
            },
          ],
        },
        {
          id: 4,
          name: '用户管理',
          code: 'UserMgt',
          type: 'MENU',
          parentId: 2,
          path: '/pms/user',
          redirect: null,
          icon: 'i-fe:users',
          component: null,
          layout: null,
          keepAlive: true,
          method: null,
          description: null,
          show: true,
          enable: true,
          order: 3,
          children: [
            {
              "id": 3,
              "name": "客户管理",
              "code": "RoleMgt",
              "type": "MENU",
              "parentId": 2,
              "path": "/pms/client",
              "redirect": null,
              "icon": "i-fe:user",
              "component": "/src/views/pms/client/index.vue",
              "layout": null,
              "keepAlive": null,
              "method": null,
              "description": null,
              "show": true,
              "enable": true,
              "order": 2,
              "children": [
                {
                  id: 13,
                  name: '创建新用户',
                  code: 'AddClient',
                  type: 'BUTTON',
                  parentId: 4,
                  path: null,
                  redirect: null,
                  icon: null,
                  component: null,
                  layout: null,
                  keepAlive: null,
                  method: null,
                  description: null,
                  show: true,
                  enable: true,
                  order: 1,
                },
              ]
            },
            {
              "id": 4,
              "name": "供应商管理",
              "code": "AuditMgt",
              "type": "MENU",
              "parentId": 2,
              "path": "/pms/supplier",
              "redirect": null,
              "icon": "i-fe:user",
              "component": "/src/views/pms/supplier/index.vue",
              "layout": null,
              "keepAlive": null,
              "method": null,
              "description": null,
              "show": true,
              "enable": true,
              "order": 2,
              "children": [
                {
                  id: 13,
                  name: '创建新用户',
                  code: 'AddSupplier',
                  type: 'BUTTON',
                  parentId: 4,
                  path: null,
                  redirect: null,
                  icon: null,
                  component: null,
                  layout: null,
                  keepAlive: null,
                  method: null,
                  description: null,
                  show: true,
                  enable: true,
                  order: 1,
                },
              ]
            }
          ],
        },
        {
          id: 5,
          name: '消息管理',
          code: 'messageMgt',
          type: 'MENU',
          parentId: null,
          path: '/message',
          redirect: null,
          icon: 'i-fe:shopping-bag',
          component: '/src/views/message/index.vue',
          layout: null,
          keepAlive: false,
          method: null,
          description: null,
          show: true,
          enable: true,
          order: 4,
          children: [
            {
              id: 555,
              name: '创建消息',
              code: 'AddMessage',
              type: 'BUTTON',
              parentId: 1,
              path: null,
              redirect: null,
              icon: null,
              component: null,
              layout: null,
              keepAlive: null,
              method: null,
              description: null,
              show: true,
              enable: true,
              order: 1,
            },
          ],
        },
        {
          id: 8,
          name: '个人资料',
          code: 'UserProfile',
          type: 'MENU',
          parentId: null,
          path: '/profile',
          redirect: null,
          icon: 'i-fe:user',
          component: '/src/views/profile/index.vue',
          layout: null,
          keepAlive: null,
          method: null,
          description: null,
          show: false,
          enable: true,
          order: 99,
        },
      ]
      userStore.setUser(user)
      permissionStore.setPermissions(permissions)
      const routeComponents = import.meta.glob('@/views/**/*.vue')
      permissionStore.accessRoutes.forEach((route) => {
        route.component = routeComponents[route.component] || undefined
        !router.hasRoute(route.name) && router.addRoute(route)
      })
      return { ...to, replace: true }
    }

    const routes = router.getRoutes()
    if (routes.find((route) => route.name === to.name)) return true

    // 判断是无权限还是404
    const { data: hasMenu } = await api.validateMenuPath(to.path)
    return hasMenu
      ? { name: '403', query: { path: to.fullPath }, state: { from: 'permission-guard' } }
      : { name: '404', query: { path: to.fullPath } }
  })
}
